<template>
  <a-modal width="800px" v-model:visible="visible" @ok="handleOk" @cancel="handleCancel">
    <template #title>
      {{ title }}
    </template>
    <a-form labelAlign="right"  >

        <!-- 配置组件 -->
      <a-form-item  label="配置名称">
        <a-input v-model="myDto.name"
            placeholder="请输入配置名称..."
        />
      </a-form-item>

      <!-- 轮播图数据 -->
      <a-form-item label="轮播图图片">
        <!-- bbm自写组件 -->
        <ImgUpload @del-img="delImg" @select="selectImg" :src="myImg" ></ImgUpload>
      </a-form-item>

      <a-form-item  label="店铺介绍">
        <a-textarea v-model="myDto.description"></a-textarea>
      </a-form-item>

      <a-form-item  label="经营范围">
        <a-textarea v-model="myDto.businessScope"></a-textarea>
      </a-form-item>
      <a-form-item label="店铺地址">
        <a-textarea v-model="myDto.address"></a-textarea>
      </a-form-item>
      <a-form-item  label="联系方式">
        <a-textarea v-model="myDto.phone"></a-textarea>
      </a-form-item>

      <a-form-item label="配置状态">
        <a-select v-model="myDto.status"  placeholder="请选择状态">
          <a-option :value="1">启用</a-option>
          <a-option :value="0">停用</a-option>
        </a-select>
      </a-form-item>

    </a-form>

  </a-modal>
</template>

<script lang="ts" setup> 
import { Notification } from "@arco-design/web-vue";
import ImgUpload, { type img } from "@/components/ImgUpload/index.vue";
import { ref } from "vue";
import { addAboutMe, putAboutMe, putAboutMeImg, type MyDto } from "@/apis/my";
import { useUserStore } from "@/stores";
import data from "@/mock/_data/area";
// 组件绑定状态(是否显示表单)
const visible: Ref<Boolean> = defineModel("visible", {
  type: Boolean,
  default: false
})

const emit = defineEmits(["ok"])
// 表单数据
// ts对其数据进行约束
const myDto: Ref<MyDto> = defineModel("dto", {
  type: Object,
  default: {
    id: 0,
    name: "",
    file: [],
    description: "",
    businessScope: "",
    address: "",
    phone: "",
    status: 0,
    updateBy: useUserStore().userInfo.id
  }
})

// 图片组件
const myImg: Ref<img[]> = defineModel("img", {
  type: Array<img>,
  default: []
})

// 表单标题
const props = defineProps({
  title: {
    type: String,
    default: "配置单"
  },

})

/**
 * 选择图片
 */
const selectImg = (data: Ref<img[]>) => {
  myImg.value = data.value
}

/**
 * 删除图片
 */
const delImg = (data: Ref<img[]>) => {
  myImg.value = data.value
}


// 点击确认按钮之后进行发送
const handleOk = async () => {
  // 关闭悬浮窗
  visible.value = !visible.value;
  clearAboutMeFormData();
  if (props.title === "新增配置") {
    await new Promise(resolve => {
      newMe().then(res => {
        if (res) {
          Notification.success({
            title: '成功',
            content: 'success!',
            duration: 3000,
          })
        } else {
          Notification.error({
            title: '失败',
            content: 'error',
            duration: 3000
          })
        }
        resolve(res);
      })
    })
  }else{
    await new Promise(resolve =>{
      updataAboutMe().then(res => {
        resolve(res);
      })
    })
  }
  // 修改暂时不写
  emit("ok");
}

const handleCancel = () => {
  visible.value = !visible.value;
  clearAboutMeFormData();
}


/**
 * 清空表单
 */

const clearAboutMeFormData = () => {
  myDto.value = {
    id: 0,
    name: "",
    file: [],
    description: "",
    businessScope: "",
    address: "",
    phone: "",
    status: 0,
    updateBy: ""
  }
  myImg.value = []
}


// 更新列表操作
const updataAboutMe= async()=>{
  let ossId = "";
  let aboudMeId = myDto.value.id;
  let formData = new FormData();

  // 将ossid循环放入
  myImg.value.forEach(i =>{
    if(!i.isNow){
      ossId += i.id + ","
    }
  });

  ossId = ossId.substring(0,ossId.length - 1);
  myDto.value.file = [];
  // 循环添加文件数据
  myImg.value.forEach(i=>{
    if(i.isNow){
      formData.append("img",i.file)
    }
  })
  // 发送更新请求
  await new Promise(resolve =>{
    putAboutMe(myDto.value).then(res=>{
      resolve(res)
      if (res) {
        Notification.success({
          title: '成功',
          content: 'success!',
          duration: 3000,
        })
      } else {
        Notification.error({
          title: '失败',
          content: 'error',
          duration: 3000
        })
      }
    })
  })

  if (formData.get("img") == null) {
    formData.append("img", new Blob())
  }

 formData.append("ossId",ossId);
 formData.append("user",useUserStore().userInfo.id);
 formData.append("id",aboudMeId+""); 

  await new Promise(resolve =>{
    putAboutMeImg(formData).then(res=>{
      resolve(res);
    })
  })
}


  const newMe = async () => {
  let formData = new FormData();
  // 添加对应字段
  formData.append("name", myDto.value.name);
  formData.append("description", myDto.value.description);
  formData.append("businessScope", myDto.value.businessScope);
  formData.append("address", myDto.value.address);
  formData.append("phone", myDto.value.phone);
  formData.append("status", myDto.value.status + "");
  // 获取用户id
  formData.append("user", useUserStore().userInfo.id);


  //添加图片
  for (let i = 0; i < myImg.value.length; i++) {
    formData.append("file", myImg.value[i].file, myImg.value[i].fileName)
  }

  if (myImg.value.length == 0) {
    //没有套装图片
    formData.append("img", new Blob, "undefined")

  }

  return await addAboutMe(formData).then(res => {
    if (res.data["success"]) {
      // 查看返回数据是否为false
      return res.data["success"];
    } else {
      return res.data["success"];
    }

  })
}


</script>

<style setup> 

</style>
